/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package fantasy;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.DocumentQuery;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.docs.DocumentEntry;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.FolderEntry;
import com.google.gdata.data.docs.PresentationEntry;
import com.google.gdata.data.docs.SpreadsheetEntry;
import com.google.gdata.util.ServiceException;

/**
 * @author dpollack
 *
 */
public class GDocCreateFolderServlet extends HttpServlet {
	
	private DocsService client = new DocsService("dhpollack-dhpollack944-v6");

	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		GOAuth g = new GOAuth();
		try {
			log("Getting Google Access Tokens for " + user.getNickname());
			Key k = new KeyFactory.Builder(GOAuth.class.getSimpleName(), user.getNickname()).getKey();
			g = pm.getObjectById(GOAuth.class, k);
		} catch (JDOObjectNotFoundException e) {
			log("User hasn't done the OAuth dance");
			return;
		}
		
		String ACCESS_TOKEN = g.getAccessToken();
		String TOKEN_SECRET = g.getAccessTokenSecret();

		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
		oauthParameters.setOAuthConsumerKey("dhpollack944.appspot.com");
		oauthParameters.setOAuthConsumerSecret("5sLdLvnBuYa+fpcWdzie9ndr");
		oauthParameters.setOAuthToken(ACCESS_TOKEN);
		oauthParameters.setOAuthTokenSecret(TOKEN_SECRET);
		
		try {
			client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
		} catch (OAuthException e) {
			// TODO Auto-generated catch block
			log("OAuthException: " + e.toString());
			e.printStackTrace();
			return;
		}
		
		DocumentListEntry folderEntry = null;
		try {
			folderEntry = createFolder("DHPollack944");
			log("Resource ID: " + folderEntry.getResourceId());
			log("Resource Type: " + folderEntry.getType());
			log("Resource Title: " + folderEntry.getTitle());
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			log("ServiceException");
			e.printStackTrace();
		}

		Query query = pm.newQuery(LeagueSettings.class);
		try {
			List<LeagueSettings> results = (List<LeagueSettings>) query.execute();
			log("Results: " + results.size());
			if(results.iterator().hasNext()) {
				for(LeagueSettings l : results) {
					String foldersFeedUri = ((MediaContent) folderEntry.getContent()).getUri();
					
					URL url = new URL(foldersFeedUri);
					
					DocumentListEntry createdEntry = createNewDocument(l.getGameType() + " - " + l.getLeagueName(), "spreadsheet", url);

					GoogleLeagueDoc docInfo = new GoogleLeagueDoc();
					Key key = KeyFactory.createKey(GoogleLeagueDoc.class.getSimpleName(),l.getLeagueKey());
					
					docInfo.setLeagueKey(key);
					docInfo.setDocResourceId(createdEntry.getResourceId());
					docInfo.setDocFolder(folderEntry.getResourceId());
					docInfo.setDocName(createdEntry.getTitle().toString());
					docInfo.setUserKey(KeyFactory.createKey(UserTable.class.getSimpleName(), user.getNickname()));
					
					pm.makePersistent(docInfo);
					log("Resource ID: " + createdEntry.getResourceId());
					log("Resource URL: " + createdEntry.getHtmlLink().getHref());
				}
			} else {
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			query.closeAll();
			pm.close();
		}
		log("Servlet Finished");


		
	}
	
    public DocumentListEntry createNewDocument(String title, String type, URL uri)
    throws IOException, ServiceException {

    	DocumentListEntry newEntry = null;
    	if (type.equals("document")) {
    		newEntry = new DocumentEntry();
    	} else if (type.equals("presentation")) {
    		newEntry = new PresentationEntry();
    	} else if (type.equals("spreadsheet")) {
    		newEntry = new SpreadsheetEntry();
    	}
    	newEntry.setTitle(new PlainTextConstruct(title));

    	return client.insert(uri, newEntry);
    }

    public DocumentListEntry createNewDocument(String title, String type)
        throws MalformedURLException, IOException, ServiceException {
      return createNewDocument(title, type, new URL("https://docs.google.com/feeds/default/private/full/"));
    }
	
	public DocumentListEntry createFolder(String title) throws IOException, ServiceException {
		
		URL folderUrl = new URL("https://docs.google.com/feeds/default/private/full/-/folder");

		DocumentQuery query = new DocumentQuery(folderUrl);
		query.setTitleQuery(title);
		query.setTitleExact(true);
		DocumentListFeed folderFeed = client.getFeed(query, DocumentListFeed.class);
		if(!folderFeed.getEntries().isEmpty()) {
			log("Folder Already Found");
			DocumentListEntry folderEntry = folderFeed.getEntries().get(0);
			return folderEntry;
		}
		
		
		URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
		DocumentListEntry newEntry = new FolderEntry();
		newEntry.setTitle(new PlainTextConstruct(title));
		log("Creating New Folder");
		return client.insert(feedUrl, newEntry);

	}
	
	

	
}
